#include "qstylesheetproperty.h"

#include "stylesheetitem/qstylesheetitemfactory.h"
#include "stylesheetitem/qabstractstylesheetitem.h"
#include "stylesheetitem/stylesheetstruct.h"

#include "../xmlobject.h"
#include "../qpropertyfactory.h"

QStylesheetProperty::QStylesheetProperty(QAbstractProperty *parent):
    QAbstractProperty(parent)
{
    set_property("type","StyleSheet");
    set_attribute(ATTR_RESET_ABLEABLE,false);
}

QString QStylesheetProperty::get_value_text()
{
    return tr("Clicked for more");
}

QIcon QStylesheetProperty::get_value_icon()
{
    return QIcon();
}

void QStylesheetProperty::fromObject(XMLObject *xml)
{
    if(xml==NULL)
    {
        return;
    }

    QMapIterator<QString,QString>      it(xml->get_propertys());

    while(it.hasNext())
    {
        it.next();
        m_propertys.insert(it.key(),it.value());
    }

    QAbstractStylesheetItem *maker=QStylesheetItemFactory::createItem(get_property("name").toString());

    if(maker==NULL)
    {
        return;
    }

    tagStylesheetItems items;

    QList<XMLObject*> list=xml->get_children();

    foreach(XMLObject* c,list)
    {

        tagStylesheetItem item;
        maker->clear();
        maker->read(c);
        item=maker->value().value<tagStylesheetItem>();
        item.m_attributes.insert("title",c->get_property("title"));
        items.append(item);
    }

    delete maker;
    set_value(QVariant::fromValue<tagStylesheetItems>(items));
}

void QStylesheetProperty::toObject(XMLObject *xml)
{
    tagStylesheetItems items=m_value.value<tagStylesheetItems>();
    if(items.size()==0)
    {
        return;
    }
    xml->clear();
    xml->set_title(m_propertys.value("name").toString());

    QMap<QString,QVariant> pros=m_propertys;
    pros.remove("name");
    pros.remove("value");
    QMapIterator<QString,QVariant>      it(pros);

    while(it.hasNext())
    {
        it.next();
        xml->set_property(it.key(),it.value().toString());
    }
    QAbstractStylesheetItem *maker=QStylesheetItemFactory::createItem(get_property("name").toString());
    if(maker!=NULL)
    {
        foreach(tagStylesheetItem item,items)
        {
            maker->setProperty("title",item.m_attributes.value("title").toString());
            maker->setValue(QVariant::fromValue<tagStylesheetItem>(item));
            XMLObject *c=new XMLObject(xml);
            maker->write(c);
        }

        delete maker;
    }
}

QString QStylesheetProperty::get_property_name()
{
    return "StyleSheet";
}

qRegisterProperty(QStylesheetProperty)
